#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtWidgets/QMainWindow>
#include <QFileDialog>

using namespace cv;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    Py_Initialize();

    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    Py_Finalize();
    delete ui;
}

void MainWindow::LabelDisplayMat(QLabel *label, Mat mat)
{
    Mat rgb;
    QImage Img;
//    ui->label->clear();
    if(mat.channels() == 3) //RGB
    {
        cvtColor(mat,rgb,CV_BGR2RGB);
        Img = QImage((const uchar * )(rgb.data),rgb.cols,rgb.rows,rgb.cols * rgb.channels(),QImage::Format_RGB888);
    }
    else
    {
        Img = QImage((const uchar * )(mat.data),mat.rows,mat.cols * mat.channels(),QImage::Format_Indexed8);
    }
    label->setPixmap(QPixmap::fromImage(Img));
    label->resize(label->pixmap()->size());
    label->show();
}

void MainWindow::on_selectPgotoPushButton_clicked()
{
    ui->testLabel->clear();
    ui->label->clear();
    ui->resultLabel->clear();
    img_name = QFileDialog::getOpenFileName( this, tr("Open Image"), ".",tr("Image Files(*.png *.jpg *.jpeg *.bmp)"));

    if(img_name.length()<=0)return;
    src=imread(img_name.toUtf8().data());

    int init_cols = 150;
    int init_rows = 150;
    cv::resize(src,src,Size(init_cols,init_rows));


    ImgPreProcessing img_pre_prc(src);

    img_pre_prc.makePreProcessing();
    imshow("hsv",img_pre_prc.getHSVImg());

    imshow("morphology",img_pre_prc.getMorphologyImg());

    imshow("cut",img_pre_prc.getCutImg());

    imshow("cuttedGray",img_pre_prc.getCuttedGrayImg());

    imshow("decentralized",img_pre_prc.getDecentralizedImg());

//    imwrite("/media/wyl/COCO/报告预处理/hsv.bmp",img_pre_prc.getHSVImg());
//    imwrite("/media/wyl/COCO/报告预处理/morphology.bmp",img_pre_prc.getMorphologyImg());
//    imwrite("/media/wyl/COCO/报告预处理/cut.bmp",img_pre_prc.getCutImg());
//    imwrite("/media/wyl/COCO/报告预处理/cuttedGray.bmp",img_pre_prc.getCuttedGrayImg());
//    imwrite("/media/wyl/COCO/报告预处理/decentralized.bmp",img_pre_prc.getDecentralizedImg());
    LabelDisplayMat(ui->label,src);

}

void MainWindow::on_makeDataPushButton_clicked()
{
    int image_number = 54;

    int init_cols = 100;
    int init_rows = 100;

    Mat left_photo(init_cols,init_rows,CV_8UC3,Scalar(0,0,0));
    Mat right_photo(init_cols,init_rows,CV_8UC3,Scalar(0,0,0));

    for(int i = 1;i <= image_number;i++)
    {
        for (int j = 0;j < 5;j ++)
        {

            string path;
            stringstream read_path;


            read_path << "/home/wyl/QtProject/build-Face_PCA-ROS_QT-Debug/ImageData/SrcImage/"<<i<<"/"<<i<<"_"<<j<<".bmp";
            path = read_path.str();

            qDebug()<<QString::fromStdString(path);
            Mat tmp = imread(path);

            stringstream write_path_;


            cv::resize(tmp,tmp,Size(init_cols,init_rows));

            ImgPreProcessing img_pre_prc(tmp);
            img_pre_prc.makePreProcessing();
            stringstream write_path;
            if(j<4)
                write_path<<"/home/wyl/QtProject/build-Face_PCA-ROS_QT-Debug/ImageData/TrainImage/"<<i<<"/"<<i<<"_"<<j<<".bmp";
            else
                write_path<<"/home/wyl/QtProject/build-Face_PCA-ROS_QT-Debug/ImageData/TestImage/"<<i<<"/"<<i<<"_"<<j<<".bmp";

            path = write_path.str();

            qDebug()<<QString::fromStdString(path);

            imwrite(path,img_pre_prc.getCutImg());
            if(i % 2 == 0)
                left_photo = img_pre_prc.getCutImg().clone();
            else
                right_photo = img_pre_prc.getCutImg().clone();
            qDebug() <<i<<"_"<<j<<"_.bmp";
        }
        if(i > 1)
        {
            Mat mix_photo;
            hconcat(left_photo,right_photo,mix_photo);
            stringstream mix_path;
            mix_path << "/home/wyl/QtProject/build-Face_PCA-ROS_QT-Debug/ImageData/MixImage/"<<i<<".bmp";
            string path = mix_path.str();
            imwrite(path,mix_photo);
        }
    }

}

void MainWindow::on_pyPushButton_clicked()
{
    QString QtImage_path = QFileDialog::getOpenFileName( this, tr("Open Image"), ".",tr("Image Files(*.png *.jpg *.jpeg *.bmp)"));

    if(QtImage_path.length()<=0)return;
    string image_path = QtImage_path.toUtf8().data();
    Mat test_image=imread(image_path);

    LabelDisplayMat(ui->label,test_image);


    if(!Py_IsInitialized())
    {
        qDebug()<<"Py_IsInitialized() Fail";
    }
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('/home/wyl/QtProject/Face_PCA/')");

    PyObject * pyMoudle = PyImport_ImportModule("PcaOption");
    if(!pyMoudle)
    {
        qDebug()<<"pyMoudle Fail";
    }

    PyObject * pyPCAOption = PyObject_GetAttrString(pyMoudle,"PcaProcess");
    if(!pyPCAOption)
    {
        qDebug()<<"pyPCAOption Fail";
    }

    PyObject * args = PyTuple_New(1);
    PyTuple_SetItem(args, 0, Py_BuildValue("s",image_path.c_str()));

    PyObject * getReturn = PyObject_CallObject(pyPCAOption,args);
    if(getReturn)
    {
        int result_flag = PyLong_AsLong(getReturn);

        string result;
        if(result_flag != -1)
        {            
            int result_front = result_flag / 10;
            int result_back = result_flag % 10;
            stringstream result_stream;
            result_stream << result_front << "_" << result_back <<".bmp";
            result = result_stream.str();
            QString str = QString::fromStdString("Most Similar Photo : "+ result);
            ui->resultLabel->setText(str);

            Mat result_image;
            stringstream result_path_stream;
            result_path_stream<<"/home/wyl/QtProject/build-Face_PCA-ROS_QT-Debug/ImageData/TrainImage/"<<result_front<<"/"<<result;
            string result_path = result_path_stream.str();
            result_image = imread(result_path);
            LabelDisplayMat(ui->testLabel,result_image);
        }
        else
        {
            ui->testLabel->clear();
            result = "No face in picture";
            QString str = QString::fromStdString(result);
            ui->resultLabel->setText(str);
        }

    }
}

void MainWindow::on_RatePushButton_clicked()
{
    if(!Py_IsInitialized())
    {
        qDebug()<<"Py_IsInitialized() Fail";
    }
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('/home/wyl/QtProject/Face_PCA/')");

    PyObject * pyMoudle = PyImport_ImportModule("PcaOption");
    if(!pyMoudle)
    {
        qDebug()<<"pyMoudle Fail";
    }

    PyObject * pyRate = PyObject_GetAttrString(pyMoudle,"showRate");
    PyObject * pyRightRate = PyObject_GetAttrString(pyMoudle,"showRightRate");
    int right_test_number = 54;
    int rate_test_number = 20;

    PyObject * right_args = PyTuple_New(1);
    PyTuple_SetItem(right_args, 0, Py_BuildValue("i",right_test_number));

    PyObject * rate_args = PyTuple_New(1);
    PyTuple_SetItem(rate_args, 0, Py_BuildValue("i",rate_test_number));

    PyObject * getRightReturn = PyObject_CallObject(pyRightRate,right_args);
    PyObject * getRateReturn = PyObject_CallObject(pyRate,rate_args);

    auto right_result_flag = PyLong_AsLong(getRightReturn);
    auto rate_result_flag = PyLong_AsLong(getRateReturn);

    stringstream right_result_stream;
    string right_result;
    right_result_stream <<right_result_flag<<"%";
    right_result = right_result_stream.str();
    QString str = QString::fromStdString("Right Rate : "+ right_result);
    ui->right_label->setText(str);

    stringstream rate_result_stream;
    string rate_result;
    rate_result_stream <<rate_result_flag<<"%";
    rate_result = rate_result_stream.str();
    str = QString::fromStdString("Recognition Rate : "+ rate_result);
    ui->rate_label->setText(str);
}


void MainWindow::on_pushButton_clicked()
{

    QString QtImage_path = QFileDialog::getOpenFileName( this, tr("Open Image"), ".",tr("Image Files(*.png *.jpg *.jpeg *.bmp)"));

    if(QtImage_path.length()<=0)return;
    string image_path = QtImage_path.toUtf8().data();
    Mat test_image=imread(image_path);

    LabelDisplayMat(ui->label,test_image);

    string finial_result;
    if(!Py_IsInitialized())
    {
        qDebug()<<"Py_IsInitialized() Fail";
    }
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('/home/wyl/QtProject/Face_PCA/')");

    PyObject * pyMoudle = PyImport_ImportModule("PcaOption");
    if(!pyMoudle)
    {
        qDebug()<<"pyMoudle Fail";
    }

    PyObject * pyPersonsRecognition_0 = PyObject_GetAttrString(pyMoudle,"PersonsRecognitionProcess_0");
    PyObject * pyPersonsRecognition_1 = PyObject_GetAttrString(pyMoudle,"PersonsRecognitionProcess_1");
    if(!pyPersonsRecognition_0)
    {
        qDebug()<<"pypyPersonsRecognition_0 Fail";
    }

    PyObject * args = PyTuple_New(1);
    PyTuple_SetItem(args, 0, Py_BuildValue("s",image_path.c_str()));

    PyObject * getReturn_0 = PyObject_CallObject(pyPersonsRecognition_0,args);
    PyObject * getReturn_1 = PyObject_CallObject(pyPersonsRecognition_1,args);
    if(getReturn_0 && getReturn_1)
    {
        auto result_flag_0 = PyLong_AsLong(getReturn_0);
        auto result_flag_1 = PyLong_AsLong(getReturn_1);
        qDebug()<<result_flag_0<<result_flag_1;
        string result;
        if(result_flag_0 != -1)
        {
            int result_front = result_flag_0 / 10;
            int result_back = result_flag_0 % 10;
            stringstream result_stream;
            result_stream << result_front << "_" << result_back <<".bmp";
            result = result_stream.str();
            finial_result += result;

            Mat result_image;
            stringstream result_path_stream;
            result_path_stream<<"/home/wyl/QtProject/build-Face_PCA-ROS_QT-Debug/ImageData/TrainImage/"<<result_front<<"/"<<result;
            string result_path = result_path_stream.str();
            result_image = imread(result_path);
            imshow("1",result_image);
        }
        else
        {
            ui->testLabel->clear();
            result = "No face in picture";
            QString str = QString::fromStdString(result);
            ui->resultLabel->setText(str);
        }
        if(result_flag_1 != -1)
        {
            int result_front = result_flag_1 / 10;
            int result_back = result_flag_1 % 10;
            stringstream result_stream;
            result_stream << result_front << "_" << result_back <<".bmp";
            result = result_stream.str();
            finial_result += " and " + result;
            QString str = QString::fromStdString("Most Similar Photo : "+ finial_result);
            ui->resultLabel->setText(str);

            Mat result_image;
            stringstream result_path_stream;
            result_path_stream<<"/home/wyl/QtProject/build-Face_PCA-ROS_QT-Debug/ImageData/TrainImage/"<<result_front<<"/"<<result;
            string result_path = result_path_stream.str();
            result_image = imread(result_path);
            imshow("2",result_image);
        }
        else
        {
            ui->testLabel->clear();
            result = "No face in picture";
            QString str = QString::fromStdString(result);
            ui->resultLabel->setText(str);
        }

    }
}
